(ns pe.trianglepath
  (:use pe.seq))

(defn- path-to [idx cnt]
  (cond
      (= idx 0) [0]
      (= idx (dec cnt)) [(dec idx)]
      :else [idx (dec idx)]))

(defn- max-value-to [idxs prev-row]
  (apply max (map prev-row idxs)))

(defn- next-step [tr rownum row prev-row]
  (let [maxrow
        (vec (for [[idx val] (indexed-from 0 row)] (+ val (max-value-to (path-to idx (count row)) prev-row))))]
    (assoc tr rownum maxrow)))

(defn maximums [tr row]
  (if (= row (count tr))
    tr
    (let [prev-row (tr (dec row)) cur-row (tr row)]
      (recur (next-step tr row cur-row prev-row) (inc row)))))
